package bo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import thread.LoadLoggedIn;

import com.steam.splace.MainActivity;
import com.steam.splace.R;
import com.steam.splace.ViewPlaceActivity;

import dao.DataAccess;
import entity.Category;
import entity.Comment;
import entity.Message;
import entity.Place;
import entity.Region;
import entity.User;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.TextView;

public class UserFunctions {
	private JSONParser jsonParser;

	private int userid = -1;
	private String token = "";
	private String loginURL = "http://www.cogidau.com/user/login";
	private String userURL = "http://www.cogidau.com/user/";
	private String registerURL = "http://www.cogidau.com/user/add";
	private String getUserURL = "http://www.cogidau.com/user/";
	private String regionUrl = "http://www.cogidau.com/region";
	private String logOutUrl = "http://www.cogidau.com/user/signout";
	private String categoryUrl = "http://www.cogidau.com/category";
	private String resetPwUrl = "http://www.cogidau.com/user/resetpassword";
	private String addPlaceUrl = "http://www.cogidau.com/place/add";
	private String placeUrl = "http://www.cogidau.com/place/";
	private String searchPlaceUrl = "http://www.cogidau.com/place/search";
	private String searchPlaceZoneUrl = "http://www.cogidau.com/place/searchplacezone";
	private String getFavoriteUrl = "http://www.cogidau.com/favorite/";
	private String getCommentUrl = "http://www.cogidau.com/comment/";
	private String addCommentUrl = "http://www.cogidau.com/comment/add";
	private String deleteCommentUrl = "http://www.cogidau.com/comment/delete/";
	private String editUserUrl = "http://www.cogidau.com/user/edit";
	private String reportUrl = "http://www.cogidau.com/report/add";
	private String rateUrl = "http://www.cogidau.com/rate";
	private String checkTokenUrl = "http://www.cogidau.com/user/checktoken/";
	private String addFavoriteUrl = "http://www.cogidau.com/favorite/add";
	private String deleteFavoriteUrl = "http://www.cogidau.com/favorite/delete";
	private Activity parentActivity = null;
	private String votePoint = "0";

	// constructor
	public UserFunctions() {
		jsonParser = new JSONParser();
	}

	public String getVotePoint() {
		return votePoint;
	}

	public void setActivity(Activity parentActivity) {
		this.parentActivity = parentActivity;
	}

	/**
	 * function make Login Request
	 * 
	 * @param email
	 * @param password
	 * */
	public int loginUser(List<NameValuePair> params) {
		JSONParser jsonParser = new JSONParser();
		int i = -1;
		try {

			JSONObject jsonObject = (JSONObject) jsonParser.parse(httpPost(
					params, loginURL));
			Object s = jsonObject.get("error");
			if (s != null)
				i = Integer.parseInt(s.toString());
			if (i == 0) {

				User u = new User();
				u.setEmail(jsonObject.get("email").toString());
				u.setAddress(jsonObject.get("address").toString());
				u.setAccessToken(jsonObject.get("token").toString());
				u.setId(Integer.parseInt(jsonObject.get("userid").toString()));
				u.setPhone(jsonObject.get("phone").toString());
				u.setSex(jsonObject.get("sex").toString());
				u.setAvatar(jsonObject.get("avatar").toString());
				u.setInUse(1);
				SharedPreferences prefs = PreferenceManager
						.getDefaultSharedPreferences(parentActivity);
				Editor prefsEditor = prefs.edit();
				prefsEditor.putInt("uid", u.getId());
				prefsEditor.putString("token", u.getAccessToken());
				prefsEditor.commit();
				int uid = prefs.getInt("uid", -1);
				System.out.println("FRom login:" + uid);
				System.out.println("FRom login:" + u.getAccessToken());
				DataAccess da = new DataAccess(parentActivity);
				try {
					da.open();
					if (da.getUser(u.getId()) == null)
						da.insertUser(u);
					else
						da.updateUser(u);
					da.removeInUse(u.getId());
					da.close();
					System.out.println("Avatar:" + u.getAvatar());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					Log.v("insert error:", e.getMessage());
				}
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			// Log.v("undefine error:",e.getMessage());
		}
		return i;
	}

	public int resetPassword(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(httpPost(
					params, resetPwUrl));
			Object s = jsonObject.get("error");
			if (s.toString().equals("0"))
				stt = 0;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stt;
	}

	public int sendReport(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(httpPost(
					params, reportUrl));
			if (jsonObject.get("error").toString().equals("0"))
				stt = 0;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stt;
	}

	public int sendVote(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(httpPost(
					params, rateUrl));
			if (jsonObject.get("error").toString().equals("0")) {
				stt = 0;
				String point = jsonObject.get("message").toString();
				votePoint = point;
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stt;
	}

	public double[] getVote(int placeId) {
		int stt = -1;
		double[] returnVote = new double[2];
		try {
			String s = httpGET(rateUrl + "/" + placeId);
			JSONObject jsonObject = (JSONObject) jsonParser.parse(s);
			Object rated = jsonObject.get("rated");
			Object point = jsonObject.get("point");
			stt = Integer.parseInt(jsonObject.get("error").toString());
			returnVote[0] = Double.parseDouble(rated.toString());
			returnVote[1] = Double.parseDouble(point.toString());

			System.out.println("return vote get:"
					+ Integer.parseInt(point.toString()));
		} catch (Exception e) {
		}
		return returnVote;
	}

	public int deleteFavorite(int placeId) {
		int stt = -1;
		try {
			String s = httpGET(deleteFavoriteUrl + "/" + placeId);
			JSONObject jsonObject = (JSONObject) jsonParser.parse(s);
			stt = Integer.parseInt(jsonObject.get("error").toString());

			System.out.println("return favorite delete:" + s + "/" + stt);
		} catch (Exception e) {
		}
		return stt;
	}

	public int addFavorite(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(httpPost(
					params, addFavoriteUrl));
			if (jsonObject.get("error").toString().equals("0"))
				stt = 0;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stt;
	}

	public int addPlace(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(httpPost(
					params, addPlaceUrl));
			if (jsonObject.get("error").toString().equals("0"))
				stt = 0;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stt;
	}

	public int addComment(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		try {
			String s = httpPost(params, addCommentUrl);
			Log.v("return string add comment:", s);
			JSONObject jsonObject = (JSONObject) jsonParser.parse(s);
			if (jsonObject.get("error").toString().equals("0"))
				stt = 0;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stt;
	}

	public ArrayList<Comment> getComment(String placeId) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		String returnComment = httpGET(getCommentUrl + placeId);
		JSONObject jsonObject1 = null;

		int stt = 0;
		if (returnComment.contains("error"))
			stt = -1;
		ArrayList<Comment> commentArr = null;
		if (stt != -1) {
			try {
				// returnComment="["+s.substring(5,s.length()-12)+"}]";
				Log.v("comment return", returnComment);
				JSONArray jsonArray = null;
				if (returnComment != null && !returnComment.equals("")
						&& !returnComment.equals("[]"))
					jsonArray = (JSONArray) jsonParser.parse(returnComment);
				commentArr = new ArrayList<Comment>();
				if (jsonArray != null)
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject jsonObject = (JSONObject) jsonArray.get(i);
						try {
							commentArr.add(new Comment(Integer
									.parseInt((String) jsonObject
											.get("commentid")),
									Integer.parseInt((String) jsonObject
											.get("userid")), Integer
											.parseInt((String) jsonObject
													.get("placeid")),
									(String) jsonObject.get("content"),
									(String) jsonObject.get("email")));
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return commentArr;
	}

	public ArrayList<Region> getRegion() {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		String returnRegion = httpGET(regionUrl);
		JSONObject jsonObject1 = null;
		int stt = 0;
		if (returnRegion.contains("error"))
			stt = -1;
		ArrayList<Region> regionArr = null;
		if (stt != -1) {
			try {
				// returnComment="["+s.substring(5,s.length()-12)+"}]";
				Log.v("comment return", returnRegion);
				JSONArray jsonArray = null;
				if (returnRegion != null && !returnRegion.equals("")
						&& !returnRegion.equals("[]")) {
					jsonArray = (JSONArray) jsonParser.parse(returnRegion);
					regionArr = new ArrayList<Region>();
					for (int i = 0; i < jsonArray.size(); i++) {
						JSONObject jsonObject = (JSONObject) jsonArray.get(i);
						regionArr.add(new Region(Integer
								.parseInt((String) jsonObject.get("regionid")),
								(String) jsonObject.get("regionname")));
					}
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return regionArr;
	}

	public ArrayList<Place> searchPlaceZone(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		ArrayList<Place> placearr = null;
		String s = httpPost(params, searchPlaceZoneUrl);
		if (!s.contains("error")) {
			try {
				System.out.println("return place area" + s);
				JSONArray jsonArray = null;
				if (s != null && !s.equals("") && !s.equals("[]")) {
					jsonArray = (JSONArray) jsonParser.parse(s);
					placearr = new ArrayList<Place>();
					for (int i = 0; i < jsonArray.size(); i++) {

						JSONObject jsonObject = (JSONObject) jsonArray.get(i);
						placearr.add(new Place(Integer
								.parseInt((String) jsonObject.get("placeid")),
								(String) jsonObject.get("placename"),
								(String) jsonObject.get("description"), Integer
										.parseInt((String) jsonObject
												.get("regionid")), Double
										.parseDouble((String) jsonObject
												.get("longitude")), Double
										.parseDouble((String) jsonObject
												.get("latitude")), Integer
										.parseInt((String) jsonObject
												.get("categoryid"))));
					}
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return placearr;
	}

	public ArrayList<Place> searchPlace(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		ArrayList<Place> placearr = null;
		try {
			String s = httpPost(params, searchPlaceUrl);
			JSONArray jsonArray = null;
			if (s != null && !s.equals("") && !s.equals("[]")) {
				jsonArray = (JSONArray) jsonParser.parse(s);
				placearr = new ArrayList<Place>();
				for (int i = 0; i < jsonArray.size(); i++) {

					JSONObject jsonObject = (JSONObject) jsonArray.get(i);
					placearr.add(new Place(Integer.parseInt((String) jsonObject
							.get("placeid")), (String) jsonObject
							.get("placename"), (String) jsonObject
							.get("description"), Integer
							.parseInt((String) jsonObject.get("regionid")),
							Double.parseDouble((String) jsonObject
									.get("longitude")), Double
									.parseDouble((String) jsonObject
											.get("latitude")), Integer
									.parseInt((String) jsonObject
											.get("categoryid"))));
				}
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return placearr;
	}

	public int signUp(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;
		try {
			JSONObject jsonObject = (JSONObject) jsonParser.parse(httpPost(
					params, registerURL));
			// if(jsonObject.get("error").equals("0"))
			stt = Integer.parseInt(jsonObject.get("error").toString());
			if (stt == 0) {
				User u = new User();
				u.setId(Integer.parseInt(jsonObject.get("userid").toString()));
				u.setEmail(jsonObject.get("email").toString());
				// u.setAddress(jsonObject.get("address").toString());
				u.setInUse(1);
				DataAccess da = new DataAccess(parentActivity);
				try {
					da.open();
					da.insertUser(u);
					da.removeInUse(u.getId());
					da.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}

		// return json
		// Log.e("JSON", json.toString());
		return stt;
	}

	public int updateInfoUser(List<NameValuePair> params) {
		// Building Parameters
		JSONParser jsonParser = new JSONParser();
		int stt = -1;

		try {
			String str = httpPost(params, editUserUrl);
			if (!str.equals("")) {
				System.out.println("update user" + str);
				JSONObject jsonObject = (JSONObject) jsonParser.parse(str);
				Object s = jsonObject.get("error");
				if (s != null && !s.equals(""))
					stt = Integer.parseInt(s.toString());
				if (stt == 0) {
					User u = new User();
					u.setId(Integer.parseInt(params.get(0).getValue()));
					u.setEmail(params.get(1).getValue());
					// u.set(params.get(2).getValue());
					u.setAddress(params.get(3).getValue());
					u.setPhone(params.get(4).getValue());
					u.setSex(params.get(5).getValue());
					u.setAvatar(params.get(6).getValue());
					u.setInUse(1);
					DataAccess da = new DataAccess(parentActivity);

					try {
						da.open();
						da.updateUser(u);
						da.removeInUse(u.getId());
						da.close();
						System.out.println("Avatar:" + u.getAvatar());
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}

		// return json
		// Log.e("JSON", json.toString());
		return stt;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public ArrayList<Category> getCategory() {
		// Building Parameters
		String s = "";
		JSONParser jsonParser = new JSONParser();
		ArrayList<Category> category = new ArrayList<Category>();
		try {

			s = httpGET(categoryUrl);
			System.out.println("return category:" + s);
			JSONArray jsonArray = (JSONArray) jsonParser.parse(s);

			for (int i = 0; i < jsonArray.size(); i++) {

				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				category.add(new Category(Integer.parseInt((String) jsonObject
						.get("categoryid")), (String) jsonObject
						.get("categoryname"), (String) jsonObject
						.get("description"), Integer
						.parseInt((String) jsonObject.get("parentid"))));
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return category;
	}

	public ArrayList<Message> getFavorite() {
		// Building Parameters
		String s = "";
		Message favorite = null;
		JSONParser jsonParser = new JSONParser();
		ArrayList<Message> arr = new ArrayList<Message>();
		try {

			s = httpGET(getFavoriteUrl);

			System.out.println("Favorite:" + s);
			JSONArray jsonArray = (JSONArray) jsonParser.parse(s);
			for (int i = 0; i < jsonArray.size(); i++) {

				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				favorite = new Message();
				favorite.setPlaceid(Integer.parseInt(jsonObject.get("placeid")
						.toString()));
				favorite.setPlaceName((String) jsonObject.get("placename"));
				favorite.setDescription((String) jsonObject.get("description"));
				favorite.setLongtitude(Double.parseDouble(jsonObject.get(
						"longitude").toString()));
				favorite.setLatitude(Double.parseDouble(jsonObject.get(
						"latitude").toString()));
				System.out.println(favorite.getLatitude() + "/"
						+ favorite.getLongitude());
				arr.add(favorite);
			}

		} catch (Exception e) {
			System.out.println("Loi");
		}
		return arr;
	}

	public User getUser(int userID) {
		// Building Parameters
		String s = "";
		User user = null;
		JSONParser jsonParser = new JSONParser();
		try {

			s = httpGET(userURL + userID);
			JSONArray jsonArray = (JSONArray) jsonParser.parse(s);
			for (int i = 0; i < jsonArray.size(); i++) {

				JSONObject jsonObject = (JSONObject) jsonArray.get(i);
				user = new User();
				user.setId(Integer.parseInt((String) jsonObject.get("userid")));
				user.setEmail((String) jsonObject.get("email"));
				user.setPhone((String) jsonObject.get("phone"));
				user.setSex((String) jsonObject.get("sex"));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	public Place getPlace(int placeID) {
		String s = "";
		Place place = null;
		JSONParser jsonParser = new JSONParser();
		try {

			s = httpGET(placeUrl + placeID);
			JSONObject jsonObject = (JSONObject) jsonParser.parse(s);
			place = new Place(Integer.parseInt((String) jsonObject
					.get("placeid")), (String) jsonObject.get("placename"),
					(String) jsonObject.get("description"),
					Integer.parseInt((String) jsonObject.get("regionid")),
					Double.parseDouble((String) jsonObject.get("longitude")),
					Double.parseDouble((String) jsonObject.get("latitude")), 0);
			place.setAddress((String) jsonObject.get("address"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return place;
	}
/*
	public void deleteComment(int commentId) {
		String s = "";
		Place place = null;
		JSONParser jsonParser = new JSONParser();
		try {
			s = httpGET(deleteCommentUrl + commentId);
			Log.v("delete return", "");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
*/
	private String httpPost(List<NameValuePair> params, String url) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(parentActivity);
		if (parentActivity != null) {
			token = prefs.getString("token", "");
		} else
			token = "";

		post.setHeader("app", token);
		Log.v("token", token);
		StringBuffer sb = new StringBuffer();
		try {
			UrlEncodedFormEntity form;
			form = new UrlEncodedFormEntity(params, "UTF-8");
			post.setEntity(form);
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage().toString());
		}
		String returnString = convertStringReturn(sb);
		if (returnString.contains("error")) {
			JSONObject jsonObject;
			try {
				jsonObject = (JSONObject) jsonParser.parse(returnString);
				if (Integer.parseInt(jsonObject.get("error").toString()) == -1) {
					// Intent login=new Intent(parentActivity,
					// MainActivity.class);
					DataAccess da = new DataAccess(parentActivity);
					da.open();
					da.signOut();
					da.close();
					Editor prefsEditor = prefs.edit();
					// prefsEditor.putString("uid","-1");
					prefsEditor.clear();
					prefsEditor.commit();
					returnString = "";
					Intent login = new Intent(parentActivity,
							MainActivity.class);
					parentActivity.finish();
					parentActivity.startActivity(login);
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return returnString;
	}

	private String convertStringReturn(StringBuffer sb) {
		String returnString = "";
		String httpString = sb.toString();
		System.out.println(httpString);
		JSONArray jsonArray = null;
		if (httpString != null && !httpString.equals("")
				&& !httpString.equals("[]")) {
			if (httpString.contains("[")) {
				returnString += "[";
				try {
					jsonArray = (JSONArray) jsonParser.parse(httpString);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonObject = (JSONObject) jsonArray.get(i);
					returnString += "{";
					for (Object obj : jsonObject.keySet()) {
						returnString += '"' + obj.toString().toLowerCase()
								+ '"' + ':' + '"'
								+ jsonObject.get(obj.toString()) + '"' + ',';

					}
					returnString += "},";
				}

				returnString = returnString.substring(0,
						returnString.length() - 1);
				returnString += "]";
			} else {
				try {
					JSONObject jsonObject = (JSONObject) jsonParser
							.parse(httpString);
					returnString += "{";
					for (Object obj : jsonObject.keySet()) {
						returnString += '"' + obj.toString().toLowerCase()
								+ '"' + ':' + '"'
								+ jsonObject.get(obj.toString()) + '"' + ',';

					}
					returnString = returnString.substring(0,
							returnString.length() - 1);
					returnString += "}";
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		System.out.println("return post:" + returnString);
		return returnString;
	}

/*	public int checkToken() {
		int stt = -1;
		try {
			HttpClient client = new DefaultHttpClient();
			// HttpClient client = MainActivity.client;
			HttpGet get = new HttpGet(checkTokenUrl + token);
			get.setHeader("app", token);
			StringBuffer sb = new StringBuffer();
			HttpResponse response = client.execute(get);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}
			String s = convertStringReturn(sb);
			JSONObject jsonObject = (JSONObject) jsonParser.parse(s);
			stt = Integer.parseInt(jsonObject.get("error").toString());
		} catch (Exception e) {
		}
		return stt;
	}*/

	private String httpGET(String url) {
		HttpClient client = new DefaultHttpClient();
		// HttpClient client = MainActivity.client;
		HttpGet get = new HttpGet(url);
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(parentActivity);
		if (parentActivity != null) {

			token = prefs.getString("token", "");
		} else
			token = "";
		get.setHeader("app", token);
		StringBuffer sb = new StringBuffer();
		try {
			HttpResponse response = client.execute(get);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}
		} catch (Exception ex) {
		}
		String returnString = convertStringReturn(sb);
		if (returnString.contains("error")) {
			JSONObject jsonObject;
			try {
				jsonObject = (JSONObject) jsonParser.parse(returnString);
				if (Integer.parseInt(jsonObject.get("error").toString()) == -1) {
					DataAccess da = new DataAccess(parentActivity);
					da.open();
					da.signOut();
					da.close();
					Editor prefsEditor = prefs.edit();
					prefsEditor.clear();
					prefsEditor.commit();
					returnString = "";
					Intent login = new Intent(parentActivity,
							MainActivity.class);
					parentActivity.finish();
					parentActivity.startActivity(login);
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return returnString;
	}

	public String signOut(String email) {
		// Building Parameters

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("email", email));
		StringBuffer sb = new StringBuffer();
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(parentActivity);
		Editor prefsEditor = prefs.edit();
		prefsEditor.putInt("uid", -1);
		prefsEditor.putString("token", "");
		prefsEditor.commit();
		try {
			httpPost(params, logOutUrl);
			DataAccess da = new DataAccess(parentActivity);
			da.open();
			da.signOut();
			da.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// return json
		// Log.e("JSON", json.toString());
		return sb.toString();
	}

}
